package io.plus.server.command;

import io.plus.common.packet.metadata.Command;
import io.plus.server.command.command_handler.ChatCommandHandler;
import io.plus.server.command.command_handler.UserCommandHandler;
import io.plus.server.command.command_handler.auth.CloseCommandHandler;
import io.plus.server.command.command_handler.auth.HeartbeatCommandHandler;
import io.plus.server.command.command_handler.auth.LoginCommandHandler;
import io.plus.server.command.command_handler.group.JoinGroupCommandHandler;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@Data
public class CommandManager {

    private static Map<Integer, CommandHandler> commandNumberToCommandHandlerMap = new HashMap<Integer, CommandHandler>();


    static {
        registerCommandHandler(new LoginCommandHandler());
        registerCommandHandler(new HeartbeatCommandHandler());
        registerCommandHandler(new CloseCommandHandler());
        //
        registerCommandHandler(new ChatCommandHandler());
        registerCommandHandler(new JoinGroupCommandHandler());
        registerCommandHandler(new UserCommandHandler());
    }

    private CommandManager() {
    }

    public static CommandHandler registerCommandHandler(CommandHandler commandHandler) {
        if (commandHandler == null || commandHandler.command() == null) {
            return null;
        }
        int commandNumber = commandHandler.command().getNumber();
        if (Command.forNumber(commandNumber) == null) {
            throw new RuntimeException("注册cmd处理器失败,不合法的cmd命令码:" + commandNumber + ",请在Command枚举类中添加!");
        }
        if (commandNumberToCommandHandlerMap.get(commandNumber) == null) {
            //commandHandler.setUserConfiguration(userConfiguration);
            return commandNumberToCommandHandlerMap.put(commandNumber, commandHandler);
        }
        return null;
    }
    //

    public static CommandHandler getCommandHandler(Command command) {
        if (command == null) {
            return null;
        }
        return commandNumberToCommandHandlerMap.get(command.getNumber());
    }

    public static <T> T getCommand(Command command, Class<T> clazz) {
        CommandHandler commandHandler = getCommandHandler(command);
        if (commandHandler != null) {
            return (T) commandHandler;
        }
        return null;
    }


}
